package com.wlc.service.impl;

import com.wlc.mapper.RoleMapper;
import com.wlc.pojo.PageResult;
import com.wlc.pojo.Role;
import com.wlc.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class RoleServiceImpl implements RoleService {

    @Override
    public PageResult<Role> findRoleList(String roleName, String roleCode, Integer page, Integer size) {
        log.info("查询角色列表分页: roleName={}, roleCode={}, page={}, size={}",
                roleName, roleCode, page, size);

        if (page == null || page < 1) page = 1;
        if (size == null || size < 1) size = 10;

        Long total = roleMapper.selectRoleCount(roleName, roleCode);
        List<Role> roles = roleMapper.selectRoleList(roleName, roleCode, (page - 1) * size, size);

        return new PageResult<>(total, roles);
    }

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Role findById(Long id) {
        log.info("根据ID查询角色: {}", id);
        Role role = roleMapper.selectById(id);
        if (role != null) {
            List<Long> menuIds = roleMapper.selectMenuIdsByRoleId(id);
            role.setMenuIds(menuIds);
        }
        return role;
    }

    @Override
    public List<Role> findAll() {
        log.info("查询所有角色");
        return roleMapper.selectAll();
    }

    @Override
    @Transactional
    public void save(Role role) {
        log.info("新增角色: {}", role.getRoleName());

        // 校验角色编码是否已存在
        Role existingRole = roleMapper.selectByRoleCode(role.getRoleCode());
        if (existingRole != null) {
            throw new RuntimeException("角色编码已存在");
        }

        // 设置默认值（移除 isDeleted 设置）
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());

        int result = roleMapper.insert(role);
        if (result <= 0) {
            throw new RuntimeException("新增角色失败");
        }

        // 保存角色菜单关联
        if (role.getMenuIds() != null && !role.getMenuIds().isEmpty()) {
            roleMapper.insertRoleMenu(role.getId(), role.getMenuIds());
        }

        log.info("新增角色成功: {}", role.getRoleName());
    }

    @Override
    @Transactional
    public void update(Role role) {
        log.info("更新角色: {}", role.getId());

        Role existingRole = roleMapper.selectById(role.getId());
        if (existingRole == null) {
            throw new RuntimeException("角色不存在");
        }

        // 校验角色编码是否被其他角色使用
        if (role.getRoleCode() != null) {
            Role roleByCode = roleMapper.selectByRoleCode(role.getRoleCode());
            if (roleByCode != null && !roleByCode.getId().equals(role.getId())) {
                throw new RuntimeException("角色编码已被其他角色使用");
            }
        }

        role.setUpdateTime(LocalDateTime.now());
        int result = roleMapper.update(role);
        if (result <= 0) {
            throw new RuntimeException("更新角色失败");
        }

        log.info("更新角色成功: {}", role.getId());
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        log.info("删除角色: {}", id);

        Role role = roleMapper.selectById(id);
        if (role == null) {
            throw new RuntimeException("角色不存在");
        }

        // 删除角色菜单关联
        roleMapper.deleteRoleMenuByRoleId(id);

        // 改为物理删除
        int result = roleMapper.deleteById(id);
        if (result <= 0) {
            throw new RuntimeException("删除角色失败");
        }

        log.info("删除角色成功: {}", id);
    }

    @Override
    @Transactional
    public void assignMenus(Long roleId, List<Long> menuIds) {
        log.info("分配角色菜单: roleId={}, menuIds={}", roleId, menuIds);

        Role role = roleMapper.selectById(roleId);
        if (role == null) {
            throw new RuntimeException("角色不存在");
        }

        // 删除原有菜单关联
        roleMapper.deleteRoleMenuByRoleId(roleId);

        // 新增菜单关联
        if (menuIds != null && !menuIds.isEmpty()) {
            roleMapper.insertRoleMenu(roleId, menuIds);
        }

        log.info("分配角色菜单成功: roleId={}", roleId);
    }

    @Override
    public List<Long> findMenuIdsByRoleId(Long roleId) {
        log.info("查询角色菜单ID列表: roleId={}", roleId);
        return roleMapper.selectMenuIdsByRoleId(roleId);
    }
}